package com.xiaoshuidi.cloud.module.contract.service.contract.impl;


import com.alibaba.fastjson.JSONObject;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.security.core.LoginUser;
import com.xiaoshuidi.cloud.framework.security.core.util.SecurityFrameworkUtils;
import com.xiaoshuidi.cloud.module.contract.controller.admin.contract.vo.WorkbenchTotalResp;
import com.xiaoshuidi.cloud.module.contract.dal.mysql.bill.RentOrderMapper;
import com.xiaoshuidi.cloud.module.contract.enums.ErrorCodeConstants;
import com.xiaoshuidi.cloud.module.contract.service.contract.WorkbenchTotalService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@Slf4j
public class WorkbenchServiceImpl implements WorkbenchTotalService {

    private final Long KEY_EXPIRE= 3000l;

    private final RentOrderMapper rentOrderMapper;
    private final RedisTemplate redisTemplate;

    @Override
    public WorkbenchTotalResp getTotal(Long apartmentId) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException(ErrorCodeConstants.USER_NOT_LOGIN);
        }
        Long tenantId = loginUser.getTenantId();
        try {
            Object json =  redisTemplate.opsForValue().get("contract_"+apartmentId+"_"+tenantId);
            if(json==null){
                return getWorkbenchTotalResp(tenantId,apartmentId);
            }else {
                 return JSONObject.parseObject((String)json, WorkbenchTotalResp.class);
            }
        } catch (Exception e) {
            log.error("====== 获取页面总数据异常{}",e.getMessage());
            return getWorkbenchTotalResp(tenantId,apartmentId);
        }
    }

    @NotNull
    private WorkbenchTotalResp getWorkbenchTotalResp(Long tenantId,Long apartmentId) {
        //查询今日现金收入
        WorkbenchTotalResp resp = new WorkbenchTotalResp();
        //今日 租金 押金 杂费收入
        WorkbenchTotalResp workbenchTotalResp = rentOrderMapper.selectTodayTotalFeeAmount(apartmentId);
        if(workbenchTotalResp!=null){
            resp.setDepositToday(workbenchTotalResp.getDepositToday());
            resp.setExtrasToday(workbenchTotalResp.getExtrasToday());
            resp.setRentInToday(workbenchTotalResp.getRentInToday());
        }
        //应收未收
        resp.setNotReceivedTotal(rentOrderMapper.selectNotReceivedTotal(apartmentId));
//        redisTemplate.opsForValue().setIfAbsent("contract_"+apartmentId+"_"+tenantId, JSONObject.toJSONString(resp),KEY_EXPIRE, TimeUnit.SECONDS);
        return resp;
    }
}
